﻿# -*- coding:utf-8 -*-
from django.core.urlresolvers import reverse, NoReverseMatch  
from django import forms
from django.utils import simplejson  
from django.utils.safestring import mark_safe  
from django.utils.encoding import force_unicode 
from django.forms.util import ErrorList, ValidationError, flatatt





class CalendarDateTimeInput(forms.DateInput):

    class Media:
        js = ['/calendar-datetime-widget.js']
        css = {
            'all': ['calendar-datetime-widget.css']
        }

    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        #print final_attrs
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_unicode(self._format_value(value))
        html_code = u'<input%s />' % flatatt(final_attrs)    
        html_code += u'''
<script type="text/javascript">
  $( "#%s" ).datepicker({
    monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
    dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
    firstDay: 1,
    dateFormat: 'yy-mm-dd'
  });
</script>''' % final_attrs['id']
        return mark_safe(html_code)






















'''  
class AutocompleteWidget(forms.TextInput): 
    """ 
    Autocomplete widget to use with jquery-autocomplete plugin. 
 
    Widget can use for static and dynamic (AJAX-liked) data. Also 
    you can relate some fields and it's values'll posted to autocomplete 
    view. 
 
    Widget support all jquery-autocomplete options that dumped to JavaScript 
    via django.utils.simplejson. 
 
    **Note** You must init one of ``choices`` or ``choices_url`` attribute. 
    Else widget raises TypeError when rendering. 
    """  
    def __init__(self, attrs=None, choices=None, choices_url=None, options=None, related_fields=None):  
        """ 
        Optional arguments: 
        ------------------- 
 
            * ``choices`` - Static autocomplete choices (similar to choices 
            used in Select widget). 
 
            * ``choices_url`` - Path to autocomplete view or autocomplete 
            url name. 
 
            * ``options`` - jQuery autocomplete plugin options. Auto dumped 
            to JavaScript via SimpleJSON 
 
            * ``related_fields`` - Fields that relates to current (value 
            of this field will sended to autocomplete view via POST) 
        """  
        self.attrs = attrs or {}  
        self.choice, self.choices, self.choices_url = None, choices, choices_url  
        self.options = options or {}  
  
        if related_fields:  
            extra = {}  
            if isinstance(related_fields, str):  
                related_fields = list(related_fields)  
  
            for field in related_fields:  
                extra[field] = "%s_value" % field  
  
            self.extra = extra  
        else:  
            self.extra = {}  
  
    def render(self, name, value=None, attrs=None):  
        if not self.choices and not self.choices_url:  
            raise TypeError('One of "choices" or "choices_url" keyword argument must be supplied obligatory.')  
  
        if self.choices and self.choices_url:  
            raise TypeError('Only one of "choices" or "choices_url" keyword argument can be supplied.')  
  
        choices = ''  
  
        if self.choices:  
            self.set_current_choice(value)  
            choices = simplejson.dumps([unicode(v) for k, v in self.choices], ensure_ascii=False)  
            html_code = forms.HiddenInput().render(name, value=value)  
            name += '_autocomplete'  
        else:  
            #html_code = '' 
            print value 
            html_code = forms.HiddenInput().render(name, value=value, attrs={'id':name, 'value':'0' })  
  
        if self.choices_url:  
            try:  
                choices = simplejson.dumps(reverse(str(self.choices_url)))  
            except NoReverseMatch:  
                choices = simplejson.dumps(self.choices_url)  
  
        if self.options or self.extra:  
            if 'extraParams' in self.options:  
                self.options['extraParams'].update(self.extra)  
            else:  
                self.options['extraParams'] = self.extra  
  
            options = ', ' + simplejson.dumps(self.options, indent=4, sort_keys=True)  
            extra = []  
  
            for k, v in self.extra.items():  
                options = options.replace(simplejson.dumps(v), v)  
                extra.append(u"function %s() { return $('#id_%s').val(); }\n" % (v, k))  
  
            extra = u''.join(extra)  
        else:  
            extra, options = '', ''  
  
        final_attrs = self.build_attrs(attrs)  
        html_code += super(AutocompleteWidget, self).render(name+'_text', self.choice or value, attrs)  
  
        html_code += u""" 
<script type="text/javascript"><!-- 
    %s$('#%s').autocomplete(%s%s); 
    $("#%s").result(function(event, data, formatted) { $("#%s").val(data[1]);});   
--></script> 
""" % (extra, final_attrs['id'], choices, options, final_attrs['id'], name)  
  
        return mark_safe(html_code)  
  
    def set_current_choice(self, data):  
        if not self.choices:  
            raise ValueError('"choices" attribute was not defined yet.')  

        for k, v in self.choices:  
            if k == data:  
                self.choice = v  
                break  
  
    def value_from_datadict(self, data, files, name): 
        #print data 
        #print name
        
        #if name in data:
        #    print data[name]
        return data.get(name, None)
'''















'''
CLIENT_CODE = u"""
<input type="text" name="%s_text" id="%s_text"/>
<input type="hidden" name="%s" id="%s" value="" />
<script type="text/javascript">
     $(function(){
    function formatItem(row) {
        return row[1] ;
    }
    function formatResult(row) {
                return row[1];
    }
    $("#%s_text").autocomplete('%s', {
                mustMatch: true,
        formatItem: formatItem,
    formatResult: formatResult

    });
    $("#%s_text").result(function(event, data, formatted) {
              $("#%s").val(data[0]);                         

	});

     });
</script>
"""

class ModelAutoCompleteWidget(forms.TextInput):
    """ widget autocomplete for text fields
    """
    html_id = ''
    def __init__(self, 
                 lookup_url=None, 
                 *args, **kw):
        super(forms.widgets.TextInput, self).__init__(*args, **kw)
        # url for Datasource
        self.lookup_url = lookup_url
       

    def render(self, name, value, attrs=None):
        if value == None:
            value = u''
        html_id = attrs.get('id', name)
        self.html_id = html_id

        lookup_url = self.lookup_url
        detail_url = u'123'#reverse('ajax_platos_detail')
        html = CLIENT_CODE % (name, html_id, name, html_id, html_id,
                                       lookup_url, html_id, html_id, detail_url)
        return mark_safe(html)


    def value_from_datadict(self, data, files, name):
        """
        Given a dictionary of data and this widget's name, returns the value
        of this widget. Returns None if it's not provided.
        """

        return data.get(name, None)
                









                
                
                
                
class ModelAutoCompleteField(forms.ChoiceField):
    """
    Autocomplete form field for Model Model
    """
    model = None
    url = None

    def __init__(self, model,  lookup_url, *args, **kwargs):
        self.model, self.url = model,  lookup_url
        super(ModelAutoCompleteField, self).__init__(
            widget = AutocompleteWidget(choices_url=self.url),
            max_length=255,
            *args, **kwargs)

    def clean(self, value):
        
        print value
        try: 
            #obj = self.model.objects.get(pk=value)
            obj = self.model.objects.get(**{'pk': value})
            print obj
        except self.model.DoesNotExist:
            raise ValidationError(u'Invalid item selected')            
        return obj    
'''                    